package com.winterwar.web;

import java.net.InetSocketAddress;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import com.winterwar.base.Convention;
import com.winterwar.service.ConventionManager;

import net.spy.memcached.*;
public class ConventionAction extends DispatchAction{

	private static Log log = LogFactory.getLog(ConventionAction.class);
	private ConventionManager mgr= null;
	
	public void setManager(ConventionManager mgr) {
		this.mgr = mgr;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
								HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting delete...");
		}
		log.info("Starting delete on : " + request.getParameter("convention.conID"));
		mgr.remove(request.getParameter("convention.conID"));
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("convention.deleted"));
		saveMessages(request, messages);
		return list(mapping, form, request, response);
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting edit...");
		}
		DynaActionForm conventionForm = (DynaActionForm) form;
		String conID = request.getParameter("conID");
		
		if(conID != null){
			Convention con = mgr.get(conID);
			if(con == null){
				ActionMessages errors = new ActionMessages();
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("convention.missing"));
				saveErrors(request, errors);
				
				return mapping.findForward("list");
			} else {
				request.setAttribute("convention", con);
			}
			conventionForm.set("convention", con);
		}
		return mapping.findForward("edit");
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		request.setAttribute("conventions", mgr.getAll());
		
		return mapping.findForward("list");
		
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}

		Random gen = new Random(new Date().getTime());
		HttpSession session = request.getSession();
		DynaActionForm conventionForm = (DynaActionForm) form;
		
		if(session.getAttribute("randFormID").toString().equals(request.getParameter("formID").toString())){
			Convention con = (Convention) conventionForm.get("convention");
			if(con.getEventRegistrationOpen() == null)
				con.setEventRegistrationOpen(new Boolean(false));
			if(con.getEventSubmissionOpen() == null)
				con.setEventSubmissionOpen(new Boolean(false));
			if(con.getCurrent() == null)
				con.setCurrent(new Boolean(false));
			con = mgr.save(con);
			if(con.getCurrent().booleanValue()){
				List cons = mgr.getAll();
				for(int i=0;i<cons.size();i++){
					Convention otherCon = (Convention) cons.get(i);
					if(otherCon.getCurrent().booleanValue() && otherCon.getConID().intValue() != con.getConID().intValue()){
						otherCon.setCurrent(new Boolean(false));
						mgr.save(otherCon);
					}
				}
			}
			session.setAttribute("randFormID", gen.nextInt() + "");
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("convention.saved"));
			saveMessages(request, messages);
		} else {
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("user.repost"));
			saveMessages(request, messages);
		}
		return list(mapping, form, request, response);
	}

	public ActionForward getCurrentCon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
		log.debug("Grabbing the current convention...");
		}
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		Boolean registrationOpen = (Boolean) cacheClient.get("WW_Reg_Open");
		Boolean submissionOpen = (Boolean) cacheClient.get("WW_Sub_Open");
		String conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;
		
		if(registrationOpen == null || submissionOpen == null || conID == null){
			Convention con = mgr.getCurrentCon();
			registrationOpen = con.getEventRegistrationOpen();
			submissionOpen = con.getEventSubmissionOpen();
			
			cacheClient.set("WW_Reg_Open", 86400, registrationOpen);
			cacheClient.set("WW_Sub_Open", 86400, submissionOpen);
			cacheClient.set("Curr_Con_ID", 86400, con.getConID().toString());
		}
		request.setAttribute("registrationOpen", registrationOpen.booleanValue());
		request.setAttribute("submissionsOpen", submissionOpen.booleanValue());
		request.setAttribute("currentConID", conID);
		return mapping.findForward("success");
	}
}